package com.xuanzuo.birthday.helper;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.xuanzuo.birthday.model.User;
import com.xuanzuo.birthday.service.Birthday;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class UserDataHelper {
    //数据库版本
    private static int DB_VERSION = 1;
    private SQLiteDatabase db;
    private UserSqliteHelper dbHelper;
    
    public UserDataHelper(Context context){
        dbHelper=new UserSqliteHelper(context, dbHelper.TB_NAME, null, DB_VERSION);
        db= dbHelper.getWritableDatabase();
    }
    
    public void close()
    {
        db.close();
        dbHelper.close();
    }
    
    //获取users表中的UserID、Access Token、Access Secret的记录
    public List<User> getUserList(Boolean isSimple)
    {
        List<User> userList = new ArrayList<User>();
        Cursor cursor=db.query(UserSqliteHelper.TB_NAME, null, null, null, null, null, User.ID+" DESC");
        cursor.moveToFirst();
        while(!cursor.isAfterLast()&& (cursor.getString(1)!=null)){
            User user=new User();
            user.setId(Integer.parseInt(cursor.getString(0)));
            user.setUserid(cursor.getString(1));
            user.setToken(cursor.getString(2));
            user.setTokensecret(cursor.getString(3));
            if(!isSimple){
            user.setUsername(cursor.getString(4));
            ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5)); 
            Drawable icon= Drawable.createFromStream(stream, "image");
            user.setIcon(icon);
            }
            userList.add(user);
            cursor.moveToNext();
        }
        cursor.close();
        return userList;
    }
    
    //判断users表中的是否包含某个UserID的记录
    public Boolean haveUser(String UserId, String mediaType)
    {
        Boolean b=false;
        Cursor cursor=db.query(UserSqliteHelper.TB_NAME, null, User.USERID + "=" + UserId + " and "+User.MEDIATYPE + "=" +Birthday.getInstance().getSelectedMedia(), null, null, null,null);
        b=cursor.moveToFirst();
        Log.e("HaveUserInfo",b.toString());
        cursor.close();
        return b;
    }

    //添加users表的记录
    public Long saveUserInfo(User user)
    {
        ContentValues values = new ContentValues();
        values.put(User.USERID, user.getUserid());
        values.put(User.TOKEN, user.getToken());
        values.put(User.TOKENSECRET, user.getTokensecret());
        Long uid = db.insert(UserSqliteHelper.TB_NAME, User.ID, values);
        Log.e("SaveUserInfo",uid+"");
        return uid;
    }
    
    //更新users表的记录，根据UserId更新用户昵称和用户图标
    public int updateUserInfo(String userName,Bitmap userIcon,String UserId)
    {
        ContentValues values = new ContentValues();
        values.put(User.USERNAME, userName);
        // BLOB类型  
        final ByteArrayOutputStream os = new ByteArrayOutputStream();  
        // 将Bitmap压缩成PNG编码，质量为100%存储          
        userIcon.compress(Bitmap.CompressFormat.PNG, 100, os);   
        // 构造SQLite的Content对象，这里也可以使用raw  
        values.put(User.ICON, os.toByteArray());
        int id= db.update(UserSqliteHelper.TB_NAME, values, User.USERID + "=" + UserId, null);
        Log.e("UpdateUserInfo2",id+"");
        return id;
    }
    
    //更新users表的记录
    public int updateUserInfo(User user)
    {
        ContentValues values = new ContentValues();
        values.put(User.USERID, user.getUserid());
        values.put(User.TOKEN, user.getToken());
        values.put(User.TOKENSECRET, user.getTokensecret());
        int id= db.update(UserSqliteHelper.TB_NAME, values, User.USERID + "=" + user.getUserid(), null);
        Log.e("UpdateUserInfo",id+"");
        return id;
    }
    
    //删除users表的记录
    public int delUserInfo(String UserId){
        int id=  db.delete(UserSqliteHelper.TB_NAME, User.USERID +"="+UserId, null);
        Log.e("DelUserInfo",id+"");
        return id;
    }
    
    public User getUserByName(String userName){
		User user = new User();
		try{
	    	Cursor cursor = db.rawQuery("select * from "+UserSqliteHelper.TB_NAME+" where "+User.USERNAME+"=?", new String[]{userName});
	    	if(cursor.getCount() > 0 && cursor.moveToFirst()){
	    		String id = cursor.getString(0);
	    		String userId = cursor.getString(1);
	    		String token = cursor.getString(2);
	    		String tokenSecret = cursor.getString(3);
	    		String name = cursor.getString(4);
	            ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5)); 
	            Drawable icon= Drawable.createFromStream(stream, "image");
	    		user.setId(Integer.parseInt(id));
	    		user.setUserid(userId);
	    		user.setToken(token);
	    		user.setTokensecret(tokenSecret);
	    		user.setUsername(userName);
	    		user.setIcon(icon);
	    	}
	    	cursor.close();
	    	return user;
		}catch (Exception e) {
			return null;
		}
    }
    

    public User getUserById(String idstr){
		User user = new User();
		try{
	    	Cursor cursor = db.rawQuery("select * from "+UserSqliteHelper.TB_NAME+" where "+User.ID+"=?", new String[]{idstr});
	    	if(cursor.getCount() > 0 && cursor.moveToFirst()){
	    		String id = cursor.getString(0);
	    		String userId = cursor.getString(1);
	    		String token = cursor.getString(2);
	    		String tokenSecret = cursor.getString(3);
	    		String name = cursor.getString(4);
	            ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5)); 
	            Drawable icon= Drawable.createFromStream(stream, "image");
	    		user.setId(Integer.parseInt(id));
	    		user.setUserid(userId);
	    		user.setToken(token);
	    		user.setTokensecret(tokenSecret);
	    		user.setUsername(name);
	    		user.setIcon(icon);
	    	}
	    	cursor.close();
	    	return user;
		}catch (Exception e) {
			return null;
		}
    }
}
